import axios from 'axios';
import qs from 'qs';
import Vue from 'vue';
import router from './../router'
axios.defaults.timeout = 360000;       
              
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';    
axios.defaults.headers.post['Accept'] = '*/*';
axios.defaults.baseURL = '/api';
axios.interceptors.request.use((config) => {
    Vue.prototype.$toast.loading({duration: 0, forbidClick: true});
    let data = config.data;
    if (localStorage.getItem('token')) {
        config.headers['token'] = localStorage.getItem('token');
        data = Object.assign({token: localStorage.getItem('token')}, data);
    }
    if(config.method  === 'post'){
        config.data = qs.stringify(data);
    }
    return config;
},(error) =>{
    return Promise.reject(error);
});

axios.interceptors.response.use((res) =>{
    Vue.prototype.$toast.clear();
    if (res.status === 200) {
        let errorCode = [-40101, -40102, -40103, -40301];
        if (errorCode.includes(res.data.status)) {
            router.push('/login');
            res.data.message = '请先登录账号'; 
        }
        Vue.prototype.$toast.clear();
        return res.data;
    } else {
        Vue.prototype.$toast.fail(`请求错误`); 
    }
}, (error) => {
    Vue.prototype.$toast.clear();
    Vue.prototype.$toast.fail(
       `请求错误：${error.response.statusText} ${error.response.status}`,
    );
    return Promise.reject(error);
});

export default axios;